import openpyxl
from pathlib import Path
from docu_kit.runs.run import Run


class Window_Run(Run):
    def read_replace_table(self, word_replace_table_path):
        """
        读取替换表格。

        Args:
            word_replace_table_path (str): 替换表格（Excel 文件）的路径。

        Returns:
            tuple: 包含两个列表，分别是要查找的旧文本列表和用于替换的新文本列表。

        Raises:
            RuntimeError: 当 Excel 表中不存在 '查找' 或 '替换' 列时抛出此异常。
        """
        # 读取 Excel 文件
        wb = openpyxl.load_workbook(word_replace_table_path, data_only=True)
        ws = wb.active  # 获取活动工作表

        # 获取标题行并查找目标列索引
        title_row = next(ws.iter_rows(min_row=1, max_row=1, values_only=True))
        title_row = [str(cell).strip() if cell is not None else "" for cell in title_row]

        try:
            find_col_idx = title_row.index("查找")
            replace_col_idx = title_row.index("替换")
        except ValueError:
            raise RuntimeError("Excel 表中不存在 '查找' 或 '替换' 列。")

        old_words = []
        new_words = []

        # 遍历数据行收集替换内容
        for row in ws.iter_rows(min_row=2, values_only=True):
            find_val = str(row[find_col_idx]) if row[find_col_idx] is not None else ""
            replace_val = str(row[replace_col_idx]) if row[replace_col_idx] is not None else ""
            old_words.append(find_val)
            new_words.append(replace_val)

        return old_words, new_words

    def batch_generate_file(self, generate_folder_path):
        """
        运行程序，批量生成文件。

        Args:
            generate_folder_path (str): 生成文件夹的路径。
        """
        self.logger.info("开始生成")
        generate_folder_path = Path(generate_folder_path)
        template_folder_path = generate_folder_path / "模板文件夹"
        word_replace_table_path = generate_folder_path / "替换表.xlsx"
        target_folder_path = generate_folder_path / "目标文件夹"
        self.logger.info("复制模板文件夹")
        self.copy_folder(template_folder_path, target_folder_path)
        self.logger.info("复制完成")
        self.logger.info("读取替换表")
        old_words, new_words = self.read_replace_table(word_replace_table_path)
        self.logger.info("读取完成")
        self.logger.info("替换内容")

        def execute_func(file_path):
            file_path = Path(file_path)
            if file_path.suffix == ".docx" or file_path.suffix == ".doc":
                self.logger.info(f"替换文件{file_path}内容")
                self.replace_word_content(str(file_path), old_words, new_words)
            elif file_path.suffix == ".xlsx" or file_path.suffix == ".xls":
                self.logger.info(f"替换文件{file_path}内容")
                self.replace_excel_content(str(file_path), old_words, new_words)

        self.deep_search_folder(target_folder_path, execute_func)
        self.logger.info("替换完成")
        self.logger.info("生成完成")
